<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" :width="800" align-center draggable overflow>
        <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="120px" label-position="top">
            <el-form-item label="名称" prop="title">
                <el-input v-model="form.title" placeholder="请输入名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="编号" prop="code">
                <el-input v-model="form.code" placeholder="编号" clearable></el-input>
            </el-form-item>
            <el-form-item label="图片" prop="image">
                <sc-upload-multiple height="100" width="100" v-model="form.image" draggable ></sc-upload-multiple>
            </el-form-item>
            <el-form-item label="颜色" prop="colors">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="checkColor">选择颜色</el-button>
                <el-input v-model="colors_name" type="textarea" :rows="4" placeholder="颜色" clearable></el-input>
            </el-form-item>
            <el-form-item label="是否展示" prop="is_show">
                <el-switch v-model="form.is_show" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
        </el-form>
        <template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
        <select-color v-if="dialog.color" ref="colorDialog" @success="handleSuccess" @closed="dialog.color=false" :query="{ is_show: 1 }"></select-color>
	</el-dialog>
</template>

<script>
import selectColor from '../color/selectColor.vue';

export default {
  components: { selectColor },
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增样本',
				edit: '编辑样本',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
            dialog: {
                color: false
            },
			//表单数据
			form: {
				id: "",
                title: "",
                code: "",
                image: "",
                colors: "",
                is_show: 1,
			},
			//验证规则
			rules: {
				title: [{ required: true, message: '请输入名称' }],
				code: [{ required: true, message: '请输入编号' }],
			},
            colors_name: "",
		}
	},
	mounted() {
	},
	methods: {
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = [];
					if (this.form.id) {
						res = await this.$API.basic.sample.edit.post(this.form);
					} else {
						res = await this.$API.basic.sample.add.post(this.form);
					}
					this.isSaveing = false;
					if (res.code == 1) {
						this.$emit('success', this.form, this.mode)
						this.visible = false;
						this.$message.success("操作成功")
					} else {
						this.$alert(res.message, "提示", { type: 'error' })
					}
				} else {
					return false;
				}
			})
		},
		//表单注入数据
		async setData(data) {
			this.form.id = data.id
			this.form.title = data.title
			this.form.code = data.code
			this.form.image = data.image
			// this.form.colors = [data.colors_ids]
            let array = []
            data.colors_ids.split(',').map(item=>{
                array.push(item)
            })
            this.form.colors = array
			this.form.is_show = data.is_show
			this.colors_name = data.colors
		},
        checkColor(){
            this.dialog.color = true
            this.$nextTick(() => {
                this.$refs.colorDialog.open('add')
            })
        },
        handleSuccess(data){
            // 使用Set进行id去重，并合并已有选择
            let idSet = new Set(this.form.colors || []);
            let existingColorMap = {};
            
            // 先将已有颜色数据存储到map中（使用id作为唯一标识）
            if(this.form.colors && this.colors_name){
                const existingIds = this.form.colors;
                const existingColors = this.colors_name.split(',');
                existingIds.forEach((id, index) => {
                    if(existingColors[index]){
                        existingColorMap[id] = existingColors[index];
                    }
                });
            }
            
            // 添加新选择的颜色
            data.forEach(item => {
                idSet.add(item.id);
                existingColorMap[item.id] = item.color_code + '#' + item.zh_name;
            });
            
            // 转换为数组
            const uniqueIds = Array.from(idSet);
            console.log('uniqueIds :>> ', uniqueIds);
            this.form.colors = uniqueIds;
            
            // 处理颜色名称显示，按照id的顺序生成颜色名称字符串
            this.colors_name = uniqueIds.map(id => existingColorMap[id]).filter(Boolean).join(',');
        },
	}
}
</script>

<style scoped>
.el-card {
	height: 720px;
	overflow-y: scroll;
}
</style>
